package com.yanyu.init.controller;


import com.yanyu.init.common.BaseResponse;
import com.yanyu.init.common.ErrorCode;
import com.yanyu.init.common.ResultUtils;
import com.yanyu.init.exception.BusinessException;
import com.yanyu.init.model.dto.AuthLoginRequest;
import com.yanyu.init.model.vo.LoginUserVO;
import com.yanyu.init.service.UserService;
import com.yanyu.init.utils.JWTUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "管理后台 - 认证")
@RestController
@RequestMapping("/system/auth")
public class AuthController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public BaseResponse<String> authLogin(@RequestBody AuthLoginRequest authLoginRequest, HttpServletRequest request){
        if (authLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = authLoginRequest.getUserAccount();
        String userPassword = authLoginRequest.getUserPassword();
        Map<String,String> map=new HashMap<>();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数为空", "请求参数为空");
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        map.put("id",String.valueOf(loginUserVO.getId()));
        map.put("username",loginUserVO.getUserName());
        map.put("userRole",loginUserVO.getUserRole());
        return ResultUtils.success(JWTUtils.createToken(map));
    }
}
